﻿using CrawlerFramework.Repository;
using log4net;
using System;
using System.Reflection;

namespace CrawlerFramework.Models
{
    public static class LinkExtension
    {
        /// <summary>
        /// Update CrawlDate and CrawlStatus value before crawling
        /// </summary>
        public static void BeginExecution(this Link link)
        {            
            using (var repo = new LinkRepository())
            {
                link.StartDate = DateTime.Now;
                link.CrawlStatus = CrawlStatus.Processing;
                repo.Edit(link);
                repo.Save();
            }
        }

        /// <summary>
        /// Update CrawlStatus after crawling finished
        /// </summary>
        public static void EndExecution(this Link link, CrawlStatus crawlStatus)
        {
            link.CrawlStatus = crawlStatus;
            link.EndDate = DateTime.Now;
            using (var repo = new LinkRepository())
            {
                repo.Edit(link);
                repo.Save();
            }
        }

        public static bool ShouldCrawl(this Link link)
        {
            var notCrawlCondition = link.StartDate == null;
            var crawledToDay = link.EndDate.HasValue && link.EndDate.Value.Date == DateTime.Now.Date;

            return notCrawlCondition || !crawledToDay;
        }
    }
}